<?php

namespace App\Models\Review;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use MongoDB\Client;

class ActivityFormModel extends Model
{
    use HasFactory;
    protected $connection="review";
    protected $table="tbl_activity_forms";
    protected $guarded=[];
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
    public static function parseSubmitForm($form_id,Request $request){
        $xmlfile=self::where([
            "uni_id"=>$form_id,
            "status"=>1
        ])->value('file');
        if(!empty($xmlfile)){
            $xml=simplexml_load_file($xmlfile) or die('load activity form model xml file error');
            $fields=$xml->children();
            $form=[];
            foreach($fields as $name=>$elem){
                $v=$request->json($name);
                if($v!==null){
                    $type=(((array)$elem['type'])[0]);
                    $form[$name]=$v;
                }
            }
            return $form;
        }
        return null;
    }
    public static function makeXml($action,$fields,&$xml){
        foreach($fields as $v){
            $name=$v['name']??null;
            $type=$v['type']??'input';//input hidden area radio checkbox select date
            $items=$v['items']??null;
            $title=$v['title']??null;
            $description=$v['description']??null;
            $_default=$v['default']??null;
            $s="<{$name} type='{$type}' title='{$title}' description='{$description}'>";
            if(!empty($_default)){
                if(!is_array($_default)){
                    $_default=[$_default];
                }
            }
            if(!empty($items)){
                if(!is_array($items)){
                    $items=[$items];
                }
                foreach($items as $itm){
                    $is_def=!empty($_default)&&in_array($itm,$_default)?" default=\"true\"":"";
                    $s.="\r\n<item{$is_def}>{$itm}</item>";
                }
            }
            $s.="\r\n</{$name}>\r\n";
            $xml.=$s;
        }
        return $xml;
    }
    public static function makeHtml($xmlfile,$activity_id){
        $doc=simplexml_load_file($xmlfile) or die('load activity form model xml file error');
        $fields=$doc->children();
        $form=[];
        foreach($fields as $name=>$elem){
            $type=(((array)$elem['type'])[0]);
            $title=(((array)$elem['title'])[0]);
            $field=[
                "type"=>$type,
                "title"=>$title
            ];
            $items=$elem->children();
            if(!empty($items)&&count($items)){
                $field['items']=[];
                foreach($items as $v){
                if(isset($v['default'])){
                    $def=((array)$v['default'])[0];
                    $field['items'][]=[
                        "value"=>(((array)$v)[0]),
                        "default"=>(bool)$def
                    ];
                }else{
                    $field['items'][]=[
                        "value"=>(((array)$v)[0]),
                    ];
                }
                }
            }
            $form[$name]=$field;
        }
        $html="<form id='activity_{$activity_id}_form'>";
        foreach($form as $k=>$v){
            $title=$v['title'];
            $html.="<label for='{$k}'>{$title}：</label>";
            switch($v['type']){
                case 'name':
                case 'bodycard':
                case 'mobile':
                case 'address':
                case 'age':
                    $html.="<input data-validator='".$v['type']."' name='{$k}'/>";
                    break;
                case 'date':
                    $html.="<datepicker name='{$k}' mode='date'/>";
                    break;
                case 'datetime':
                    $html.="<datepicker name='{$k}' mode='datetime'/>";
                    break;
                case 'radio':
                    foreach($v['items'] as $v1){
                        if(isset($v1['default'])&&$v1['default']){
                     $html.="<radio name='{$k}' value='{$v1['value']}' checked='checked'/>";
                        }else{
                     $html.="<radio name='{$k}' value='{$v1['value']}'/>";
                        }
                    }
                    break;
                case 'checkbox':
                    foreach($v['items'] as $v1){
                        if(isset($v1['default'])&&$v1['default']){
                     $html.="<checkbox name='{$k}[]' value='{$v1['value']}' checked='checked'/>";
                        }else{
                     $html.="<checkbox name='{$k}[]' value='{$v1['value']}'/>";
                        }
                    }
                    break;
            }
            $html.="<br/>";
        }
        return $html."</form>";
    }
    public static function shot($data){
        $form_id=$data['form_id']??null;
        $action=self::where('uni_id',$form_id)->value('action');
        if(empty($action))
        $action='vote';
        switch($action){
            case 'vote':{
                return self::vote($data);
            }
            case 'review':{
                return self::review($data);
            }
        }
    }
    private static function vote($data){
        $activity_id=$data['activity_id']??null;
        $form_id=$data['form_id']??null;
        $object_id=$data['object_id']??null;
        $user_id=$data['user_id']??null;
        $user_ip=$data['user_ip']??null;
        $client=new Client("mongodb://mongo_ZeQxdC:mongo_5aWXeK@172.30.17.120:27017");
        $mongo=$client->selectDatabase("online_review");
        $coll=$mongo->selectCollection("activity_form_review_list");
        $where=[];
        if(!empty($activity_id))
        $where["activity_id"]=$activity_id;
        if(!empty($form_id))
        $where["form_id"]=$form_id;
        if(!empty($object_id))
        $where["object_id"]=$object_id;
        if(!empty($user_id))
        $where["user_id"]=$user_id;
        if(!empty($user_ip))
        $where["user_ip"]=$user_ip;
        $data=$coll->aggregate([
            ['$match'=>$where],
            ['$group'=>[
            "_id"=>null,
            "cnt"=>['$count'=>(object)[]]
            ]],
            ['$project'=>['cnt'=>1,'_id'=>0]]
        ]);
        $v=[];
        foreach($data as $v1){
            $v[]=$v1;
        }
        if(empty($v)){
         return $coll->insertOne([
            "activity_id"=>$activity_id,
            "form_id"=>$form_id,
            "form_id"=>$form_id,
            "object_id"=>$object_id,
            "user_id"=>$user_id,
            "user_ip"=>$user_ip,
            "created_at"=>date('Y-m-d H:i:s'),
            "updated_at"=>date('Y-m-d H:i:s'),
         ])->getInsertedId();
        }else{
         return $v;
        }
    }
    private static function review($data){
        return null;
    }
}
